// src/utils/request.js
import axios from 'axios'
import { BASE_URL } from "../config/config";
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 0) {
      // 可以根据不同的错误码进行不同的处理
      switch (res.code) {
      case 401:  // 未授权
        localStorage.removeItem('token')
        break
      case 403:  // 禁止访问
        ElMessage.error('没有权限访问')
        break
      default:
        ElMessage.error(res.message || '发生错误')
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error('响应错误:', error)
    const { status } = error.response
    switch (status) {
    case 401:
      // 清除token并跳转到登录页
      localStorage.removeItem('token')
      break
    case 404:
      break
    case 500:
      break
    default:
      
    }
    return Promise.reject(error.response.data)
  },
)

export default service